package com.jiuyin.dianjing.ui.fragment.match;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.adapter.SectionQuickAdapter;
import com.jiuyin.dianjing.api.constant.ApiConstant;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.interfaces.ProgressDialogCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.entity.MySection;
import com.jiuyin.dianjing.event.RefreshEvent;
import com.jiuyin.dianjing.model.CompeteDetail;
import com.jiuyin.dianjing.model.MatchDataDetail;
import com.jiuyin.dianjing.model.MatchDataModel;
import com.jiuyin.dianjing.ui.activity.match.MatchDataActivity;
import com.jiuyin.dianjing.ui.fragment.base.BaseLazyFragment;
import com.jiuyin.dianjing.util.LogUtil;
import com.jiuyin.dianjing.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_COMPET_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_IS_CREATOR;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_POST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_RACE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_STAGE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;

/**
 * 比赛数据
 */
public class FragmentMatchGameData extends BaseLazyFragment {
    @BindView(R.id.rcv_page)
    RecyclerView mRcvPage;
    @BindView(R.id.tv_title)
    TextView mTitle;
    @BindView(R.id.empty)
    View mEmptyLayout;
    @BindView(R.id.empty_text)
    TextView mEmptyText;
    @BindView(R.id.empty_image)
    ImageView mEmptyImage;

    private SectionQuickAdapter mAdapter;
    List<MySection> mData = new ArrayList<>();
    private static final String CREATOR = "1";
    private String mRace = DEFAULT_RACE_VALUE;
    private String mStage = DEFAULT_STAGE_VALUE;

    private static final String DEFAULT_STAGE_VALUE = "1";
    /**
     * 预选赛
     */
    private static final String DEFAULT_RACE_VALUE = "0";
    /**
     * 半决赛
     */
    private static final String DEFAULT_RACE_VALUE1 = "1";
    /**
     * 总决赛
     */
    private static final String DEFAULT_RACE_VALUE2 = "2";
    /**
     * 循环赛
     */
    private static final String DEFAULT_RACE_VALUE3 = "3";

    private String mCompetitionId;
    /**
     * 是否是创建者
     */
    private String mIsCreator;

    private int mTactics;

    public static FragmentMatchGameData newInstance(String competitionId, String isCreator) {
        Bundle bundle = new Bundle();
        bundle.putString(KEY_COMPET_ID, competitionId);
        bundle.putString(KEY_IS_CREATOR, isCreator);
        FragmentMatchGameData fragmentGame = new FragmentMatchGameData();
        fragmentGame.setArguments(bundle);
        return fragmentGame;
    }

    @Override
    public void fetchData() {
        HashMap hashMap = new HashMap();
        hashMap.put(KEY_TOKEN, HelperApplication.getToken());
        hashMap.put(ApiConstant.KEY_COMPETITIONID, mCompetitionId);
        JSONObject data = new JSONObject(hashMap);
        ApiResultCallback request = new ApiResultCallback() {
            @Override
            public void onSuccess(JsonObject data) {
                CompeteDetail compete = new Gson().fromJson(data, CompeteDetail.class);
                mTactics = compete.tactics;
                mCompetitionId = compete.course.competition_id;
                fetchMatchData(DEFAULT_STAGE_VALUE, DEFAULT_RACE_VALUE);
            }

            @Override
            public void onFail(String msg) {
                ToastUtil.showShort(msg);
            }

            @Override
            public void onError(String msg) {
                LogUtil.log(msg);
            }
        };
        ProgressDialogCallback defaultProgressDialogCallback = new ProgressDialogCallback() {
            @Override
            public void showProgressDialog() {
                showLoading();
            }

            @Override
            public void dismissProgressDialog() {
                dismissLoading();
            }
        };
        ServerApi.post(ApiEnum.APP_COMPETE_DETAIL_API.getUrl(), data, null, defaultProgressDialogCallback, d -> addDisposable(d), request);
    }

    /**
     *获取阶段赛事数据
     * @param stage
     * @param race
     */
    private void fetchMatchData(String stage, String race) {
        HashMap hashMap = new HashMap();
        hashMap.put(ApiConstant.KEY_TOKEN, HelperApplication.getToken());
        hashMap.put(KEY_STAGE, stage);
        hashMap.put(KEY_RACE, race);
        hashMap.put(ApiConstant.KEY_TACTICS, mTactics);
        hashMap.put(ApiConstant.KEY_COMPETITION_ID, mCompetitionId);
        JSONObject data = new JSONObject(hashMap);
        ApiResultCallback request = new ApiResultCallback() {

            @Override
            public void onSuccess(JsonObject data) {
                LogUtil.log("FragmentMatchGameData onSuccess data = " + data);
                if (data.has(KEY_STAGE)) {
                    if (DEFAULT_RACE_VALUE.equals(mRace)) {
                        mData.add(new MySection(true, getString(R.string.match_preliminary)));
                    }else if (DEFAULT_RACE_VALUE3.equals(mRace)) {
                        mData.add(new MySection(true, getString(R.string.match_cycle)));
                    }
                    else if (DEFAULT_RACE_VALUE1.equals(mRace)) {
                        mData.add(new MySection(true, getString(R.string.match_semifinal)));
                    }

                    MatchDataDetail matchDataDetail = new Gson().fromJson(data, MatchDataDetail.class);
                    fillData(matchDataDetail, mRace);
                    if (data.has(KEY_RACE)) {
                        mRace = data.get(KEY_RACE).getAsString();
                    }
                    mStage = data.get(KEY_STAGE).getAsString();
                    fetchMatchData(mStage, mRace);
                } else {
                    if (DEFAULT_RACE_VALUE2.equals(mRace)) {
                        mData.add(new MySection(true, getString(R.string.match_final)));
                    }
                    MatchDataDetail matchDataDetail = new Gson().fromJson(data, MatchDataDetail.class);
                    fillData(matchDataDetail, mRace);
                    update();
                }
            }

            @Override
            public void onFail(String msg) {
                LogUtil.log("onFail msg = " + msg);
                update();
//                ToastUtil.showShort(msg);
            }

            @Override
            public void onError(String msg) {
                LogUtil.log("onError msg = " + msg);
                ToastUtil.showShort(msg);
                update();
            }
        };
        ProgressDialogCallback defaultProgressDialogCallback = new ProgressDialogCallback() {
            @Override
            public void showProgressDialog() {
                showLoading();
            }

            @Override
            public void dismissProgressDialog() {
                dismissLoading();
            }
        };
        ServerApi.post(ApiEnum.APP_COMPETE_DATA_STAGE_RACE_API.getUrl(), data, null, defaultProgressDialogCallback, d -> addDisposable(d), request);
    }

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_match_game_data;
    }

    @Override
    protected void initData() {
        mCompetitionId = getArguments().getString(KEY_COMPET_ID);
        mIsCreator = getArguments().getString(KEY_IS_CREATOR);
        mAdapter = new SectionQuickAdapter(getActivity(), R.layout.item_game_data_info, R.layout.def_section_head, null) {
            @Override
            protected void convert(@NotNull BaseViewHolder helper, MySection item) {
                MatchDataModel model = (MatchDataModel) item.getObject();
                helper.setText(R.id.tv_player1_name, model.player1Name);
                helper.setText(R.id.tv_player1_score, model.player1Score);
                helper.setText(R.id.tv_player2_name, model.player2Name);
                helper.setText(R.id.tv_player2_score, model.player2Score);
                ImageView imageView1 = helper.getView(R.id.img_player1);
                ImageView imageView2 = helper.getView(R.id.img_player2);
                Glide.with(getActivity()).load(model.player1Logo).into(imageView1);
                Glide.with(getActivity()).load(model.player2Logo).into(imageView2);
            }
        };
        if (CREATOR.equals(mIsCreator)) {
            mAdapter.setOnItemClickListener((adapter, view, position) -> {
                MySection item = (MySection) adapter.getItem(position);
                MatchDataModel model = (MatchDataModel) item.getObject();
                Bundle bundle = new Bundle();
                bundle.putSerializable(KEY_POST, model);
                goTargetActivity(MatchDataActivity.class, bundle);
            });
        }
        mRcvPage.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        mRcvPage.setItemAnimator(new DefaultItemAnimator());
        mRcvPage.setAdapter(mAdapter);
    }

    @Override
    protected void initView() {
        mEmptyText.setText(R.string.data_null);
        mEmptyImage.setImageResource(R.drawable.ic_empty);
    }

    private void fillData(MatchDataDetail matchDataDetail, String race) {
        int dataListSize = matchDataDetail.eventDataList.size();
        for (int i = 0; i < dataListSize; i++) {
            MatchDataDetail.EventDataList eventDataList = matchDataDetail.eventDataList.get(i);
            MatchDataModel model = new MatchDataModel();
            MatchDataDetail.RecordList recordList0 = eventDataList.recordList.get(0);
            MatchDataDetail.RecordList recordList1 = eventDataList.recordList.get(1);
            int result = recordList0.grade.compareTo(recordList1.grade);
            if (0 == result) {
                model.player1Score = recordList0.grade;
                model.player1Name = recordList0.name;
                model.player1Lineup = recordList0.lineup;
                model.player1Logo = recordList0.logo;
                model.player1RecordKeepId = recordList0.recordkeep_id;

                model.player2Score = recordList1.grade;
                model.player2Name = recordList1.name;
                model.player2Lineup = recordList1.lineup;
                model.player2Logo = recordList1.logo;
                model.player2RecordKeepId = recordList1.recordkeep_id;
            } else if (result > 0) {
                model.player1Score = recordList0.grade;
                model.player1Name = recordList0.name;
                model.player1Lineup = recordList0.lineup;
                model.player1Logo = recordList0.logo;
                model.player1RecordKeepId = recordList0.recordkeep_id;

                model.player2Score = recordList1.grade;
                model.player2Name = recordList1.name;
                model.player2Lineup = recordList1.lineup;
                model.player2Logo = recordList1.logo;
                model.player2RecordKeepId = recordList1.recordkeep_id;
            } else {
                model.player1Score = recordList1.grade;
                model.player1Name = recordList1.name;
                model.player1Lineup = recordList1.lineup;
                model.player1Logo = recordList1.logo;
                model.player1RecordKeepId = recordList1.recordkeep_id;

                model.player2Score = recordList0.grade;
                model.player2Name = recordList0.name;
                model.player2Lineup = recordList0.lineup;
                model.player2Logo = recordList0.logo;
                model.player2RecordKeepId = recordList0.recordkeep_id;
            }
            model.competsingledata_id = eventDataList.competsingledata_id;
            model.race = race;
            model.competition_id = mCompetitionId;
            MySection mine = new MySection(false, model);
            mData.add(mine);
        }
    }

    private void update() {
        if (0 != mData.size()) {
            mTitle.setVisibility(View.VISIBLE);
        } else {
            showEmpty();
        }
        mAdapter.setNewInstance(mData);
    }

    /**
     * 更新数据
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RefreshEvent event) {
        if (event.clazzName.equals(getClass().getSimpleName())) {
            mData.clear();
            fetchMatchData(DEFAULT_STAGE_VALUE, DEFAULT_RACE_VALUE);
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 显示空
     */
    private void showEmpty() {
        if (0 == mAdapter.getItemCount()) {
            if (View.VISIBLE != mEmptyLayout.getVisibility()) {
                mEmptyLayout.setVisibility(View.VISIBLE);
            }
        }
    }
}
